// pages/truckCenter/addv2.js
let _page, _this;
import commonUtils from '../../utils/util.js'
import requestUtil from '../../baseRequest.js'
import requestUrls from '../../requestUrl.js'
import imageUtils from '../../utils/imageUtils.js'
import {
  $Message
} from '../../components/base/index'

let openid = wx.getStorageSync('openid')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: openid,
    truckCenter: {},
    truckInfo: {},
    //驾驶证
    mainDriverLicense: [],
    //行驶证
    vehicleLicense: [],
    truckInfoStr: '',
    showTimeSelect: false,
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    datePickerTitle: '选择出发时间',
    freeBeginTime: '',
    freeEndTime: '',
    ifPlateNumber: false,
  },
  //获取收货地址
  getReceiveAddress() {
    _this = this;
    wx.chooseLocation({
      complete: (res) => {
        const { latitude, longitude } = res;
        _this.getRealLocation(latitude, longitude);
      },
    })

  },
  getFromAddress() {
    wx.setStorageSync('truckCenter', this.data.truckCenter);
    wx.navigateTo({
      url: '/pages/truckCenter/fromAddress?orderType=truckCenter&addressType=FA',
    })

  },
  //根据经纬度获取省市县，详细地址
  getRealLocation(latitude, longitude) {
    _page = this;
    wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=VEJBZ-M5YLX-KZN4O-7VWPS-VGOFT-46FXA`,
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        //获取省市县
        const { city, province, district } = res.data.result.address_component;
        //获取详细地址
        const { recommend } = res.data.result.formatted_addresses;
        _page.setData({
          truckCenter: {
            ..._page.data.truckCenter,
            toProvinceName: province,
            toCityName: city,
            toCountyName: district,
            toAddressDetail: recommend
          }
        })
      }
    })
  },
  afterJSZRead(event) {
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl + requestUrls.uploadUrl.driverLisence;
    let filePath = file.path;
    let imgList = [];
    imageUtils.uploadImage(uploadUrl, filePath, (url) => {
      imgList.push({ url: requestUrls.baseImagePrefixUrl + url, imageUrl: url });
      this.setData({
        mainDriverLicense: imgList,
      });
      wx.setStorageSync('mainDriverLicense', imgList);
    });
  },
  afterXSZRead(event) {
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl + requestUrls.uploadUrl.drivingLisence;
    let filePath = file.path;
    let imgList = [];
    imageUtils.uploadImage(uploadUrl,filePath,(url)=>{
      imgList.push({ url: requestUrls.baseImagePrefixUrl + url, imageUrl: url })
        this.setData({
          vehicleLicense: imgList,
        });
        wx.setStorageSync('vehicleLicense', imgList);
    });
  },
  getTruckInfo() {
    wx.setStorageSync('truckCenter', this.data.truckCenter);
    wx.navigateTo({
      url: '/pages/truckCenter/truckInfo?fromPage=addv2',
    })
  },
  getTypeLength() {
    wx.setStorageSync('truckCenter', this.data.truckCenter);
    wx.navigateTo({
      url: '/pages/truckCenter/typeLength?orderType=truckCenter&fromPage=addv2',
    })
  },
  getBeginTime() {
    this.setData({
      showTimeSelect: true,
      old_freeBeginTime: this.data.freeBeginTime,
      old_freeEndTime: this.data.freeEndTime,
      freeBeginTime: '',
      freeEndTime: '',
    })

  },
  onFromCancel() {
    this.setData({
      showTimeSelect: false,
    })
  },
  onFromConfirm(event) {
    const {beginDate,endDate} = event.detail;
    this.setData({
      truckCenter:{
        ...this.data.truckCenter,
        freeBeginTime:commonUtils.formatYMDH(new Date(beginDate)),
        freeEndTime:commonUtils.formatYMDH(new Date(endDate)),
        freeTime:commonUtils.formatDate(new Date(beginDate), 'MM-dd hh')+"点--"+commonUtils.formatDate(new Date(endDate), 'MM-dd hh')+"点",
      },
    });
    this.onFromCancel();
  },
  removeJSZ() {
    this.setData({
      mainDriverLicense: [],
    })
  },
  removeXSZ() {
    this.setData({
      vehicleLicense: [],
    })
  },
  showPlateNumber() {
    this.setData({
      ifPlateNumber: true,
    })
  },
  hidePlateNumber() {
    this.setData({
      ifPlateNumber: false,
    })
  },
  changePlateNumber(event) {
    const { detail } = event;
    wx.setStorageSync('plateNumber', detail);
    this.setData({
      truckCenter: {
        ...this.data.truckCenter,
        plateNumber: detail,
      }
    })
    this.hidePlateNumber();
  },
  //发布车辆
  publishTruck() {
    if (this.checkPublishTruck()) {
      this.setData({ showLoading: true })
      let orderTruckImageList = [];
      const { mainDriverLicense, vehicleLicense, addressInfo, truckInfo, typeLength, } = this.data;
      //驾驶证
      if (mainDriverLicense && mainDriverLicense.length > 0) {
        orderTruckImageList.push({
          imageUrl: mainDriverLicense[0].imageUrl, orderTypeId: 'TRUCK_CENTER', imageTypeId: 'LICENSE_IMAGE'
        })
      }
      if (vehicleLicense && vehicleLicense.length > 0) {
        orderTruckImageList.push({
          imageUrl: vehicleLicense[0].imageUrl, orderTypeId: 'TRUCK_CENTER', imageTypeId: 'VEHICLE_LICENSE'
        })
      }

      let formData = {
        openId: openid,
        criteria: {
          truckCenter: {
            ...this.data.truckCenter,
            ...addressInfo,
            ...truckInfo,
            ...typeLength,
            orderTruckImageList
          }
        }
      };
      requestUtil.postRequest(requestUrls.truckCenter.saveTruckCenter, { ...formData }, (res) => {
        this.setData({ showLoading: false });
        if (!res.hasError) {
          wx.removeStorageSync('truckCenter');
          wx.showModal({
            title: '温馨提示',
            content: '操作成功',
            showCancel: false,
            success: res => {
              wx.switchTab({
                url: '/pages/homev2/index'
              })
            }
          })
        }
      })
    }
  },
  //校验录入数据
  checkPublishTruck() {
    const { mainDriverLicense, vehicleLicense, addressInfo, truckInfo, typeLength, truckCenter } = this.data;
    if (mainDriverLicense.length === 0) {
      this.showErrorMessage('请选择上传驾驶证');
      return false;
    }
    if (vehicleLicense.length === 0) {
      this.showErrorMessage('请选择上传行驶证');
      return false;
    }
    if (!truckInfo) {
      this.showErrorMessage('请填写车辆空间信息');
      return false;
    }
    if (!addressInfo) {
      this.showErrorMessage('请填写出发地地址');
      return false;
    }
    if (!typeLength) {
      this.showErrorMessage('请填写车型');
      return false;
    }
    if (truckCenter.plateNumber === '' || commonUtils.isEmoji(truckCenter.plateNumber)) {
      this.showErrorMessage('车牌号码不符合要求');
      return false;
    }
    if (!truckCenter.freeBeginTime || truckCenter.freeBeginTime === '') {
      this.showErrorMessage('出发时间不符合要求');
      return false;
    }
    return true;
  },
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const addressInfo = wx.getStorageSync('addressInfo');
    const truckInfo = wx.getStorageSync('truckInfo');
    const typeLength = wx.getStorageSync('typeLength');
    const truckCenter = wx.getStorageSync('truckCenter');
    const plateNumber = wx.getStorageSync('plateNumber');
    const mainDriverLicense = wx.getStorageSync('mainDriverLicense');
    const vehicleLicense = wx.getStorageSync('vehicleLicense');
    this.setData({
      addressInfo: addressInfo,
      truckInfo: truckInfo,
      typeLength: typeLength,
      mainDriverLicense,
      vehicleLicense,
      truckCenter: {
        ...truckCenter,
        plateNumber: plateNumber
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})